const Controller = require('egg').Controller
const fs = require('fs')
// node.js 路径操作对象
const path = require('path')
// egg.js Controller
const awaitWriteStream = require('await-stream-ready').write
// 管道读入一个虫洞。
const sendToWormhole = require('stream-wormhole')

class ArticleController extends Controller {

  /* 后台 */
  async uploadArticle() {
    const { ctx, config } = this
    const stream = await ctx.getFileStream();
    // 文件名:随机数+时间戳+原文件后缀
    // path.extname(stream.filename).toLocaleLowerCase()为后缀名（.jpg,.png等）
    const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
    // 图片存放在静态资源public/img文件夹下
    const target = path.join(config.baseDir, 'app/public/article', filename);
    // 生成一个文件写入 文件流
    const writeStream = fs.createWriteStream(target);
    try {
      // 异步写入文件流
      await awaitWriteStream(stream.pipe(writeStream));
    } catch (err) {
      // 如果出现错误，关闭管道
      await sendToWormhole(stream);
      throw err;
    }

    ctx.body = {
      code: '0',
      filename: path.join('/public/article', filename),
      desc: '上传成功'
    }
  }
  async getArticles() {
    try {
      const { app, ctx } = this
      const { Op } = app.Sequelize
      const { searchForm, page, limit } = ctx.request.body
      let conditions = {}
      if(!searchForm) {
        conditions = {}
      } else {
        if(!!searchForm.title) {
          conditions.title = {[Op.startsWith]: searchForm.title}
        } 
        if(!!searchForm.status) {
          conditions.status = searchForm.status
        }
      }
      const articles = await ctx.service.article.getList(conditions, page, limit)
      ctx.body = {
        code: '0',
        desc: '文章获取成功',
        articles: articles
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '文章获取失败',
        err: error
      }
    }
  }

  // 获取指定文章
  async getArticle() {
    try {
      const { ctx } = this
      const { id } = ctx.request.body
      const article = await ctx.model.Article.findByPk(id)
      ctx.body = {
        code: '0',
        desc: '文章获取成功',
        article: article
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '文章获取失败',
        err: error
      }
    }
  }

  async createArticle() {
    try {
      const { ctx } = this
      const { articleForm, category } = ctx.request.body
      await ctx.model.Article.create({
        title: articleForm.title,
        content: articleForm.content,
        picture: articleForm.imageUrl,
        category: category
      })
      ctx.body = {
        code: '0',
        desc: '文章提交成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '文章提交失败',
        err: error
      }
    }
  }

  async editArticle() {
    try {
      const { ctx } = this
      const { articleForm, id } = ctx.request.body
      // 待做：需更新updatedAt
      await ctx.model.Article.update(articleForm, {
        where: {
          id: id
        }
      })
      ctx.body = {
        code: '0',
        desc: '文章修改成功'
      }
    } catch(error) {
      const { ctx } = this
      return ctx.body = {
        code: '-1',
        desc: '文章修改失败',
        err: error
      }
    }
  }

  async deleteArticle() {
    try {
      const { ctx } = this
      const { id } = ctx.request.body
      await ctx.model.Article.destroy({
        where: {
          id: id
        }
      })
      ctx.body = {
        code: '0',
        desc: '文章删除成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '文章删除失败',
        err: error
      }
    }
  }

  async batchDeleteArticles() {
    try {
      const { app, ctx } = this
      const { Op } = app.Sequelize
      const { ids } = ctx.request.body
      await ctx.model.Article.destroy({
        where: {
          id: {
            [Op.in]: ids
          }
        }
      })
      ctx.body = {
        code: '0',
        desc: '文章批量删除成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '文章批量删除失败'
      }
    }
  }
}

module.exports = ArticleController